<template>
  <!-- 登录页面和注册页面不显示侧边栏 -->
  <div v-if="$route.name === 'login' || $route.name === 'register'" class="app-container">
    <router-view />
  </div>
  
  <!-- 其他页面显示侧边栏布局 -->
  <div v-else class="main-layout">
    <aside class="sidebar">
      <div class="sidebar-top">
        <img src="@/assets/log.png" alt="logo" class="logo-img" />
        <el-button type="primary" class="sidebar-create-btn" icon="el-icon-plus" plain @click="onCreateTask">+ 新建任务</el-button>
        <div class="user-info-card">
          <div class="user-info-main">
            <div class="user-avatar-container">
              <img class="user-avatar" src="./assets/avatar.jpg" alt="头像" />
            </div>
            <div class="user-info-text">
              <div class="user-name">陈思远</div>
              <div class="user-role">产品经理</div>
            </div>
          </div>
          <div class="user-info-actions">
            <div class="action-item">
              <el-icon><Setting /></el-icon>
              <span>设置</span>
            </div>
            <div class="action-item" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              <span>退出登录</span>
            </div>
          </div>
        </div>
      </div>
      <el-menu class="sidebar-menu" :default-active="'/'" router>
        <el-menu-item index="/">
          <el-icon><Menu /></el-icon>
          <span>全部任务</span>
        </el-menu-item>
        <el-menu-item index="today">
          <el-icon><Calendar /></el-icon>
          <span>今日待办</span>
        </el-menu-item>
        <el-menu-item index="done">
          <el-icon><Check /></el-icon>
          <span>已完成</span>
        </el-menu-item>
      </el-menu>
      <div class="sidebar-section">
        <div class="sidebar-section-title">自定义分类</div>
        <ul class="sidebar-category-list">
          <li v-for="(cat, idx) in categories" :key="cat.id">
            <el-icon v-if="idx === 0"><Menu /></el-icon>
            <el-icon v-else-if="idx === 1"><Notebook /></el-icon>
            <el-icon v-else-if="idx === 2"><User /></el-icon>
            <el-icon v-else><Document /></el-icon>
            {{ cat.name }}
          </li>
        </ul>
      </div>
      <div class="sidebar-section">
        <div class="sidebar-section-title">标签</div>
        <div class="sidebar-tags">
          <el-tag
            v-for="tag in tags"
            :key="tag.id"
            :style="{ backgroundColor: tag.color + '22', color: tag.color, border: 'none' }"
            effect="plain"
          >
            {{ tag.name }}
          </el-tag>
        </div>
      </div>
      <div class="sidebar-bottom custom-sidebar-bottom">
      </div>
    </aside>
    <main class="content">
      <router-view @show-detail="onShowDetail" />
      <TaskDetail v-if="showDetail" :task-id="currentTaskId" @close="showDetail = false" @saved="onTaskSaved" />
    </main>
  </div>
</template>

<script setup>
import TaskList from './components/TaskList.vue'
import TaskDetail from './components/TaskDetail.vue'
import { Menu, Calendar, Check, User, Notebook, Document, More, Setting, SwitchButton } from '@element-plus/icons-vue'
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import http from './utils/http'

const router = useRouter()
const route = useRoute()
const tags = ref([])
const categories = ref([])
const showDetail = ref(false)
const currentTaskId = ref(null)

// 判断当前是否在认证页面（登录/注册）
const isAuthPage = computed(() => {
  return route.name === 'login' || route.name === 'register'
})

const fetchTags = async () => {
  // 仅在非认证页面获取标签
  if (isAuthPage.value) return
  
  try {
    const response = await http('/api/tags')
    const data = await response.json()
    tags.value = data.results
  } catch (e) {
    // 可选：错误处理
  }
}

const fetchCategories = async () => {
  // 仅在非认证页面获取分类
  if (isAuthPage.value) return
  
  try {
    const response = await http('/api/categories')
    const data = await response.json()
    categories.value = data.results
  } catch (e) {
    // 可选：错误处理
  }
}

function onShowDetail(id) {
  currentTaskId.value = id
  showDetail.value = true
}

function onCreateTask() {
  currentTaskId.value = null
  showDetail.value = true
}

function onTaskSaved() {
  showDetail.value = false
  window.location.reload() //自动刷新页面
}

async function handleLogout() {
  try {
    const response = await http('/api/auth/logout/', {
      method: 'POST'
    })
    
    // 无论后端返回如何，都清除本地令牌
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('user')
    
    ElMessage.success('已退出登录')
    
    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('退出登录出错:', error)
    // 即使请求出错，也清除本地令牌并跳转
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('user')
    router.push('/login')
  }
}

onMounted(() => {
  // 只在非认证页面加载数据
  if (!isAuthPage.value) {
    fetchTags()
    fetchCategories()
  }
})
</script>

<style scoped>
.app-container {
  width: 100%;
  height: 100vh;
}
.main-layout {
  display: flex;
  min-height: 100vh;
  background: #faf8f3;
}
.sidebar {
  width: 220px;
  background: #fff;
  border-right: 1.5px solid #f0e9d2;
  display: flex;
  flex-direction: column;
  padding: 24px 0 0 0;
  box-sizing: border-box;
}
.sidebar-top {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 12px;
}
.logo-img {
  width: 56px;
  height: 56px;
  display: block;
  margin: 0 auto 18px auto;
}
.logo {
  display: none;
}
.sidebar-create-btn {
  width: 160px;
  margin-bottom: 18px;
}
.sidebar-menu {
  border: none;
  width: 100%;
  margin-bottom: 18px;
}
.sidebar-section {
  padding: 0 24px 0 24px;
  margin-bottom: 18px;
}
.sidebar-section-title {
  font-size: 13px;
  color: #b0b0b0;
  margin-bottom: 8px;
}
.sidebar-category-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.sidebar-category-list li {
  display: flex;
  align-items: center;
  font-size: 15px;
  color: #333;
  margin-bottom: 8px;
  gap: 8px;
}
.sidebar-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.sidebar-bottom {
  margin-top: auto;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.sidebar-setting-label {
  color: #888;
  font-size: 14px;
}
.content {
  flex: 1;
  padding: 0;
  background: #f7f8fa;
  min-height: 100vh;
}
.settings-icon {
  width: 32px;
  height: 32px;
  /* margin-right: 5px; */
  display: inline-block;
  vertical-align: middle;
}
.filter-row-with-search.user-bar-row {
  width: 100%;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  background: #fff;
  padding: 24px 0 24px 32px;
  border-bottom: 1px solid #f0f0f0;
  min-height: 64px;
}
.user-bar-right {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 10px;
}
.user-avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e4e7ed;
}
.user-dropdown-trigger {
  font-size: 16px;
  color: #333;
  cursor: pointer;
  display: flex;
  align-items: center;
}
.custom-search {
  flex: none;
  width: 320px;
  background: #fafbfc;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  height: 36px;
  font-size: 15px;
  margin-right: 12px;
}
/* 个人信息卡片 */
.user-info-card {
  border: none;
  border-radius: 6px;
  padding: 12px;
  margin-top: 16px;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
  transition: box-shadow 0.3s ease;
}
.user-info-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}
.user-info-main {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.user-avatar-container {
  flex-shrink: 0;
  margin-right: 12px;
}
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: none;
}
.user-info-text {
  flex-grow: 1;
}
.user-name {
  font-weight: 600;
  font-size: 16px;
  color: #222;
}
.user-role {
  font-size: 13px;
  color: #666;
  margin-top: 2px;
}
.user-info-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.action-item {
  display: flex;
  align-items: center;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
}
.action-item:hover {
  color: #1890ff;
}
.action-item .el-icon {
  margin-right: 6px;
  font-size: 18px;
}
.sidebar-bottom.custom-sidebar-bottom {
  padding-left: 0;
  padding-right: 0;
}
</style>